import { getGoods } from "@/api/goods";
import { GetGoodsReq } from "@/typings/goods";
import { GoodsRecord } from "@/views/goods/GoodsList/GoodsListType";
import { Select, SelectProps } from "antd";
import { debounce } from "lodash";
import { forwardRef, ForwardRefRenderFunction, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
import ImgTextOption from "../dataPresentation/ImgTextOption";

const { Option } = Select;

interface GoodsSelectProps extends SelectProps {
	onGoodsChange?: (goodsItem: GoodsRecord | GoodsRecord[] | null) => void;
}

export interface GoodsSelectRef {
	insertGoodsByIds: (ids: string[]) => void;
}

const GoodsSelect: ForwardRefRenderFunction<GoodsSelectRef, GoodsSelectProps> = ({ onChange, onGoodsChange, ...remainingProps }, ref) => {
	const [goodsList, setGoodsList] = useState<GoodsRecord[]>([]);
	const fetchGoods = async (value = "") => {
		const options: GetGoodsReq = {};
		if (value) options.name = value;
		const { data } = await getGoods(options);
		setGoodsList(data?.data || []);
	};
	const [additionalList, setAdditionalList] = useState<GoodsRecord[]>([]);
	const insertGoodsByIds = async (ids: string[] = []) => {
		if (!ids?.length) return;
		const { data } = await getGoods({ ids });
		setAdditionalList(data?.data || []);
	};
	useImperativeHandle(
		ref,
		() => ({
			insertGoodsByIds,
		}),
		[]
	);
	const realGoodsList = useMemo(() => {
		const objectList = [...goodsList, ...additionalList];
		return [...new Set(objectList.map(item => item._id))].map(item => objectList.find(item1 => item1._id === item) as GoodsRecord);
	}, [goodsList, additionalList]);
	const fetchGoodsDebounce = useCallback(debounce(fetchGoods, 500), []);
	useEffect(() => {
		fetchGoods();
		insertGoodsByIds();
	}, []);
	return (
		<Select
			filterOption={false}
			placeholder="选择或搜索商品"
			onSearch={fetchGoodsDebounce}
			onChange={(value, option) => {
				onChange?.(value, option);
				let goodsValue: GoodsRecord | GoodsRecord[] | null = null;
				if (remainingProps.mode === "multiple") {
					goodsValue = value.map((item: string) => realGoodsList.find(item1 => item1._id === item));
				} else {
					goodsValue = realGoodsList.find(item => item._id === value) || null;
				}
				onGoodsChange?.(goodsValue);
			}}
			{...remainingProps}
		>
			{realGoodsList.map(({ _id, name, cover }, index) => (
				<Option key={index} value={_id}>
					<ImgTextOption url={cover} name={name} />
				</Option>
			))}
		</Select>
	);
};

export default forwardRef(GoodsSelect);
